/**
 *
 * @author Doan Tuan Anh
 */

public class GameThread extends Thread{

  private boolean myShouldPause;
  private boolean myShouldStop;


  private MyGameCanvas gameCanvas;

  private long myLastRefreshTime;


  GameThread(MyGameCanvas canvas) {
    gameCanvas = canvas;
  }

  private long getWaitTime() {
    long retVal = 1;
    long difference = System.currentTimeMillis() - myLastRefreshTime;
    if(difference < 75) {
      retVal = 75 - difference;
    }
    return(retVal);
  }

  void pauseGame() {
    myShouldPause = true;
  }

  synchronized void resumeGame() {
    myShouldPause = false;
    notify();
  }

  synchronized void requestStop() {
    myShouldStop = true;
    notify();
  }

  public void run() {
    gameCanvas.flushKeys();
    myShouldStop = false;
    myShouldPause = false;
    while(true) {
      myLastRefreshTime = System.currentTimeMillis();
      if(myShouldStop) {
	break;
      }
      synchronized(this) {
	while(myShouldPause) {
	  try {
	    wait();
	  } catch(Exception e) {}
	}
      }

      gameCanvas.advance();
      
      synchronized(this) {
	try {
	  wait(getWaitTime());
	} catch(Exception e) {}
      }
    }
  }
}
